package com.jj.controller;

import com.jj.pojo.User;
import com.jj.service.DemoService;
import com.jj.util.ThreadLocalContext;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequiredArgsConstructor
public class DemoController {


    private final DemoService demoService;

    @RequestMapping("/demo")
    public String demo() {
        ThreadLocalContext.put("initUser", new User("张三", 32));

        System.out.println("controller:" + Thread.currentThread().getId());
        String demoStr = demoService.demo("你好？");

        ThreadLocalContext.clear();  // 防止内存泄漏，每次使用完毕都要清除

        return demoStr;
    }

    @RequestMapping("/demo01")
    public String demo01() {
        ThreadLocalContext.put("initUser", new User("张三", 32));
        ThreadLocalContext.clear();  // 提前进行清除，会导致获取不到，空指针


        System.out.println("controller:" + Thread.currentThread().getId());
        String demoStr = demoService.demo("你好？");



        return demoStr;
    }

    @RequestMapping("/demo02")
    public String demo02() {
        ThreadLocalContext.put("initUser", new User("张三", 32));
        ThreadLocalContext.clear();  // 提前进行清除

        ThreadLocalContext.initThreadLocalContext(new ConcurrentHashMap<String,Object>());  // 然后再重新设一个map
        ThreadLocalContext.put("initUser", new User("张三", 33));

        System.out.println("controller:" + Thread.currentThread().getId());


        String demoStr = demoService.demo("你好？");



        return demoStr;
    }

    @RequestMapping("/getInfo")
    public String getInfo(String name, int age) {
        return "server1:getInfo:" + "name:" + name + ",age:" + age;
    }
}
